import {hasOwn, isDef} from "../../../shared/util";
import {createInvoker} from "../../instance/events";

/**
 *
 * @param {Reactive} vm
 * @param {Object} listeners
 * @param {Object} oldListeners
 * @param {Function} add
 * @param {Function} remove
 */
export function updateListeners (
    vm,
    listeners,
    oldListeners,
    add,
    remove
) {
    if (isDef(listeners)) {
        for (let event in listeners) {
            const handlers = listeners[event];
            if (isDef(oldListeners[event])) {
                oldListeners[event].handlers = handlers;
                listeners[event] = oldListeners[event];
            }
            else {
                const invoker = createInvoker(vm, handlers);
                listeners[event] = invoker;
                add(event, invoker);
            }
        }
        for (let event in oldListeners) {
            if (!hasOwn(listeners, event)) {
                const invoker = oldListeners[event];
                remove(event, invoker);
            }
        }
    }
}
